import select
import subprocess

from config import Config, Env
from runner import RunnerControllor, Runable, Tailf


def register_read_event(runner_list):
    for r in runner_list:
        epoll.register(r.fd, select.EPOLLIN)


def unregister(runner_list):
    for r in runner_list:
        epoll.unregister(r.fd)


if __name__ == '__main__':
    epoll = select.epoll()
    conf = Config()
    # 获取需要监控的log,并注册监听
    runner_ctr = RunnerControllor()
    for path in conf.get_monitoring():
        cmd = Env.cmd(path)
        runner = Runable(cmd)
        # runner = Tailf(path)
        runner_ctr.add(runner)

    runner_ctr.start()

    register_read_event(runner_ctr.get_all())
    try:
        while True:
            events = epoll.poll()
            for fd, event in events:
                if event & select.EPOLLIN:
                    print(event)
                    r = runner_ctr.get_runner_by_fd(fd)
                    if not r:
                        continue
                    print(r.get_output())
                    print('-' * 50)
    except Exception as e:
        print('got exception:', e)
    finally:
        runner_ctr.stop()
        unregister(runner_ctr.get_all())
        epoll.close()
        exit(1)
